package com.delay.redis.queue;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @program: SpringBootDemos
 * @description:
 * @author: Kangsen
 * @create: 2022-07-08 14:23
 **/
@SpringBootTest
@RunWith(SpringRunner.class)
public class RedisDemoApplication {

    @Resource
    private JedisCluster jedisCluster;

    @Resource
    private JedisPool jedisPool;

    /**
     * 集群版测试
     */
    @Test
    public void contextLoads(){
        //集群的连接池 这需要redis的集群环境
        jedisCluster.set("names","sdsdsdwee");
        System.out.println(jedisCluster.get("names"));
        jedisCluster.del("name");
    }

    /**
     * 单机版测试
     */
    @Test
    public void  testJedisPool(){
        Jedis jedis = jedisPool.getResource();
        //jedis.zrem()
        long currentTimeMillis = System.currentTimeMillis();
        jedis.zadd("test-zset",currentTimeMillis,"111");
        jedis.zadd("test-zset",currentTimeMillis + 1,"222");
        jedis.zadd("test-zset",currentTimeMillis - 2,"333");
        jedis.zadd("test-zset1",currentTimeMillis + 3,"333");
        jedis.close();
    }


    @Test
    public void expireKey(){
        Jedis jedis = jedisPool.getResource();
        //jedis.zrangeByScore("test-zset", 0, System.currentTimeMillis(), 0, 1);
        Executors.newSingleThreadExecutor().submit(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    Set<String> taskIdSet = jedis.zrangeByScore("test-zset", 0, System.currentTimeMillis(), 0, 1);
                    if (taskIdSet == null || taskIdSet.isEmpty()) {
                        System.out.println("没有任务");

                    } else {
                        taskIdSet.forEach(id -> {
                            long result = jedis.zrem("test-zset", id);
                            if (result == 1L) {
                                System.out.println("从延时队列中获取到任务，taskId:" + id + " , 当前时间：" + LocalDateTime.now());
                            }
                        });
                    }
                    try {
                        TimeUnit.MILLISECONDS.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        jedis.close();
    }
}
